package cj.web.portal.controllers;

import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cj.utils.weixin.pay.Sign;
import cj.utils.weixin.pay.WXConfigUtil;

public class BaseController{
	public final static String oauth_start = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxb8851d53461b983d&redirect_uri=";
	public final static String oauth_end ="&response_type=code&scope=snsapi_base&state=1#wechat_redirect";
	//长江金服
	public static interface cjjf{
		public static String AppID="wxdb2e0dddbf042ec0";
		public static String AppSecret="48a9eeb98f26c1ed79695e75bc0906a8";
	}
	
	private static Map<String,String> wxJSConfig;
	
    public void setCookie(HttpServletResponse response,String name,String value){
        Cookie cookie = new Cookie(name.trim(), value.trim());
        cookie.setPath("/");
        cookie.setMaxAge( 622080000 );
        response.addCookie(cookie);
    }
    
    public String getCookieValueByName(HttpServletRequest request,String name){
    	Cookie[] cookies = request.getCookies();
        if(null!=cookies && cookies.length > 0){
            for(Cookie cookie : cookies){
                if( name.equals(cookie.getName()) ){
                	return cookie.getValue();
                }
            }
        }
        
        return "";
    }
    
    public boolean isLogin(HttpServletRequest request){
    	String phone = getCookieValueByName(request,"phone");
    	if(!"".equals(phone)){
    		return true;
    	}
    	return false;
    }
    
    public Map<String, String> getConfigSign(HttpServletRequest request) throws Exception{
    	String ticket = "";
    	
    	if(null != wxJSConfig){
    		Long current =  Long.valueOf(System.currentTimeMillis() / 1000);
    		Long timestamp = Long.valueOf(wxJSConfig.get("timestamp").toString());
    		if( current - timestamp > 3600){
    			ticket = refreshTicket();
    		}
    		else{
    			ticket = wxJSConfig.get("jsapi_ticket").toString();
    		}
    	}
    	else{
    		ticket = refreshTicket();
    	}
    	
    	return getSign(request, ticket);
    }
    
    private String refreshTicket() throws Exception{
    	String appid = cjjf.AppID;
		String secret = cjjf.AppSecret;
		String ticket = WXConfigUtil.returnJsapiTicket(appid, secret);
		
		return ticket;
    }

	private Map<String, String> getSign(HttpServletRequest request, String ticket) {
		String url = request.getScheme() +"://" + request.getServerName() + request.getServletPath();
	    if (request.getQueryString() != null){
	        url += "?" + request.getQueryString();
	    }
	    wxJSConfig= Sign.sign(ticket, url);
	    return wxJSConfig;
	}
    
}
